<template>
  <!-- 标题区域 -->
  <div v-if="isDialog" class="dialog-title">
    <h2 class="dialog-title-text">邮箱登录</h2>
  </div>
  <div v-else class="login-title">
    <div class="title-content">
      <img class="logo" src="@/assets/image/logo.png" alt="logo" />
      <h2 class="title-text">
        {{ WEBSITE_NAME }}
      </h2>
    </div>
  </div>

  <!-- 邮箱登录表单 -->
  <div class="login-form-container">
    <el-form
      ref="emailFormRef"
      :model="emailForm"
      :rules="emailRules"
      class="login-form"
      label-position="top"
      @submit.prevent="handleEmailLogin"
    >
      <!-- 邮箱输入框 -->
      <el-form-item label="邮箱" prop="email" class="form-item">
        <el-input
          v-model="emailForm.email"
          placeholder="请输入邮箱地址"
          size="large"
          class="login-input"
          @keyup.enter="handleEmailLogin"
        >
          <template #prefix>
            <svg-icon icon-class="email" class="input-icon" />
          </template>
        </el-input>
      </el-form-item>

      <!-- 邮箱验证码输入框 -->
      <el-form-item label="邮箱验证码" prop="emailCode" class="form-item">
        <div class="captcha-container">
          <el-input
            v-model="emailForm.emailCode"
            placeholder="请输入邮箱验证码"
            size="large"
            class="captcha-input"
            @keyup.enter="handleEmailLogin"
          >
            <template #prefix>
              <svg-icon icon-class="captcha" class="input-icon" />
            </template>
          </el-input>
          <el-button
            :disabled="!canSendCode || countdown > 0"
            :loading="sendingCode"
            class="send-code-btn"
            @click="sendEmailCode"
          >
            <span v-if="countdown > 0">{{ countdown }}s后重发</span>
            <span v-else>发送验证码</span>
          </el-button>
        </div>
      </el-form-item>

      <!-- 记住我选项 -->
      <div class="form-options">
        <el-checkbox v-model="emailForm.rememberMe" class="remember-checkbox">
          <span class="checkbox-text">记住我</span>
        </el-checkbox>
      </div>

      <!-- 登录按钮 -->
      <el-form-item class="login-button-item">
        <el-button
          :loading="loading"
          type="primary"
          size="large"
          class="login-button"
          @click="handleEmailLogin"
        >
          <span v-if="!loading" class="button-text">登录</span>
          <span v-else class="button-text">登录中...</span>
        </el-button>
      </el-form-item>

      <!-- 其他登录方式 -->
      <div class="register-link">
        <span class="register-text">其他登录方式？</span>
        <el-button link type="primary" class="register-btn" @click="$emit('switch-mode')">
          账号密码登录
        </el-button>
      </div>
    </el-form>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive } from 'vue';
import type { FormInstance } from 'element-plus';
import { ElNotification } from 'element-plus';
import SvgIcon from '@/components/common/SvgIcon/index.vue';
import { useRouter, useRoute } from 'vue-router';
import { useUserStore } from '@/store/modules/user';
import { useCommonStore } from '@/store/modules/common';
import { usePermissionStore } from '@/store/modules/permission';
import { sendEmailCaptcha, emailLoginApi } from '@/api/auth';
import { WEBSITE_NAME } from '@/constants';
import { LOGIN_DEVICE_ENUM } from '@/constants/common/login-device';

const route = useRoute();
const router = useRouter();
const UserStore = useUserStore();
const CommonStore = useCommonStore();
const PermissionStore = usePermissionStore();

const emailFormRef = ref<FormInstance>();
const loading = ref<boolean>(false);
const sendingCode = ref<boolean>(false);
const countdown = ref<number>(0);
const canSendCode = ref<boolean>(true);

defineProps({
  isDialog: {
    type: Boolean,
    default: false
  }
});

const emit = defineEmits(['switch-mode']);

// 表单验证规则
const emailRules = reactive({
  email: [
    {
      required: true,
      message: '请输入邮箱地址',
      trigger: 'blur'
    },
    {
      type: 'email',
      message: '请输入正确的邮箱格式',
      trigger: 'blur'
    }
  ],
  emailCode: [
    {
      required: true,
      message: '请输入邮箱验证码',
      trigger: 'blur'
    },
    {
      len: 6,
      message: '验证码长度为6位',
      trigger: 'blur'
    }
  ]
});

// 表单数据
const emailForm = reactive({
  email: '',
  emailCode: '',
  rememberMe: false,
  loginDevice: LOGIN_DEVICE_ENUM.PC.value.toString()
});

/**
 * 发送邮箱验证码
 */
const sendEmailCode = async () => {
  if (!emailForm.email) {
    ElNotification({
      title: '提示',
      message: '请先输入邮箱地址',
      type: 'warning'
    });
    return;
  }

  try {
    sendingCode.value = true;
    await sendEmailCaptcha(emailForm.email);

    ElNotification({
      title: '发送成功',
      message: '验证码已发送到您的邮箱',
      type: 'success'
    });

    // 开始倒计时
    countdown.value = 60;
    canSendCode.value = false;

    const timer = setInterval(() => {
      countdown.value--;
      if (countdown.value <= 0) {
        clearInterval(timer);
        canSendCode.value = true;
      }
    }, 1000);
  } catch (error) {
    console.error('发送验证码失败:', error);
  } finally {
    sendingCode.value = false;
  }
};

/**
 * 邮箱登录
 */
const handleEmailLogin = async () => {
  if (!emailFormRef.value) return;

  try {
    const valid = await emailFormRef.value.validate();
    if (!valid) return;

    loading.value = true;

    await UserStore.login(emailForm);
    await CommonStore.getDictionary();
    await PermissionStore.generateRoutes(UserStore.roles);

    // 移除这里的手动重定向逻辑，现在由tokenExpiredManager统一处理
    ElNotification({
      title: '登录成功',
      message: `欢迎回来，${UserStore.userInfo.username}！`,
      type: 'success',
      duration: 3000
    });
  } catch (error) {
    console.error('登录失败:', error);
  } finally {
    loading.value = false;
  }
};
</script>

<style lang="scss" scoped>
@use '../index.scss';

// 标题样式
.dialog-title {
  text-align: center;
  margin-bottom: 16px;

  .dialog-title-text {
    font-size: 24px;
    font-weight: 600;
    color: #303133;
    margin: 0;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
    background-clip: text;
  }
}

.login-title {
  text-align: center;
  margin-bottom: 20px;

  .title-content {
    display: flex;
    align-items: center;
    justify-content: center;
    margin-bottom: 4px;

    .logo {
      width: 40px;
      height: 40px;
      margin-right: 12px;
      border-radius: 8px;
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
    }

    .title-text {
      font-size: 26px;
      font-weight: 700;
      color: #303133;
      margin: 0;
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      -webkit-background-clip: text;
      -webkit-text-fill-color: transparent;
      background-clip: text;
    }
  }
}

// 表单容器
.login-form-container {
  .login-form {
    .form-item {
      margin-bottom: 12px;

      .input-label {
        margin-bottom: 4px;

        .label-text {
          font-size: 12px;
          font-weight: 500;
          color: #606266;
        }
      }

      // 输入框样式
      :deep(.login-input) {
        .el-input__wrapper {
          height: 40px;
          border-radius: 8px;
          border: 2px solid #e4e7ed;
          transition: all 0.3s ease;
          box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);

          &:hover {
            border-color: #c0c4cc;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
          }

          &.is-focus {
            border-color: #409eff;
            box-shadow: 0 4px 16px rgba(64, 158, 255, 0.2);
          }
        }

        .el-input__inner {
          height: 36px;
          font-size: 14px;
          color: #303133;

          &::placeholder {
            color: #c0c4cc;
            font-size: 12px;
          }
        }

        .input-icon {
          font-size: 15px;
          color: #909399;
          margin-right: 8px;
        }
      }
    }

    // 验证码容器
    .captcha-container {
      display: flex;
      gap: 8px;

      .captcha-input {
        flex: 1;
      }

      .send-code-btn {
        width: 100px;
        height: 40px;
        border-radius: 8px;
        font-size: 12px;
        font-weight: 500;
        border: 2px solid #e4e7ed;
        background: #fff;
        color: #606266;
        transition: all 0.3s ease;

        &:hover:not(:disabled) {
          border-color: #409eff;
          color: #409eff;
          background: #f0f9ff;
        }

        &:disabled {
          background: #f5f7fa;
          color: #c0c4cc;
          border-color: #e4e7ed;
          cursor: not-allowed;
        }
      }
    }

    // 表单选项
    .form-options {
      display: flex;
      justify-content: flex-start;
      align-items: center;
      margin-bottom: 14px;

      .remember-checkbox {
        :deep(.el-checkbox__label) {
          .checkbox-text {
            font-size: 12px;
            color: #606266;
            font-weight: 400;
          }
        }

        :deep(.el-checkbox__input.is-checked .el-checkbox__inner) {
          background-color: #409eff;
          border-color: #409eff;
        }
      }
    }

    // 登录按钮
    .login-button-item {
      margin-bottom: 12px;

      .login-button {
        width: 100%;
        height: 44px;
        font-size: 14px;
        font-weight: 600;
        border-radius: 8px;
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        border: none;
        box-shadow: 0 4px 16px rgba(102, 126, 234, 0.3);
        transition: all 0.3s ease;

        &:hover {
          transform: translateY(-2px);
          box-shadow: 0 8px 24px rgba(102, 126, 234, 0.4);
        }

        &:active {
          transform: translateY(0);
        }

        .button-text {
          letter-spacing: 1px;
        }

        &.is-loading {
          background: linear-gradient(135deg, #a8b3f0 0%, #b19bc8 100%);
        }
      }
    }

    // 其他登录方式链接
    .register-link {
      text-align: center;

      .register-text {
        font-size: 12px;
        color: #909399;
        margin-right: 8px;
      }

      .register-btn {
        font-size: 12px;
        font-weight: 600;
        padding: 0;

        &:hover {
          color: #337ecc;
        }
      }
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  .login-title {
    .title-content {
      .logo {
        width: 32px;
        height: 32px;
        margin-right: 8px;
      }

      .title-text {
        font-size: 22px;
      }
    }
  }

  .login-form-container {
    .login-form {
      .captcha-container {
        .send-code-btn {
          width: 80px;
          font-size: 10px;
        }
      }

      .login-button-item .login-button {
        height: 40px;
        font-size: 13px;
      }
    }
  }
}

// 动画效果
@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.login-form-container {
  animation: fadeInUp 0.6s ease-out;
}

.form-item {
  animation: fadeInUp 0.6s ease-out;
  animation-fill-mode: both;

  @for $i from 1 through 6 {
    &:nth-child(#{$i}) {
      animation-delay: #{$i * 0.1}s;
    }
  }
}
</style>
